import 'package:flutter_admin/api/odoo/sale_inquiry_form_odoo_api.dart';
import 'package:flutter_admin/api/odoo/sale_inquiry_product_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_form.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_product.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input_num.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/sale_offer_form/sale_offer_price.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';

class SaleOfferDetailList extends StatefulWidget {
  SaleInquiryForm? saleInquiryForm;
  SaleOfferDetailList({required this.saleInquiryForm, Key? key})
      : super(key: key);

  @override
  _SaleOfferDetailListState createState() => _SaleOfferDetailListState();
}

class _SaleOfferDetailListState extends State<SaleOfferDetailList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  late SaleInquiryForm saleInquiryForm;
  SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct();
  List<SaleInquiryProduct> selectedList = [];
  // List tableList = [];
  @override
  void initState() {
    super.initState();
    this.saleInquiryForm = widget.saleInquiryForm ?? SaleInquiryForm();

    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 300,
            label: '报价单位',
            enable: false,
            value: saleInquiryForm.companyName,
          ),
          CryInput(
            width: 300,
            label: '事业部',
            enable: false,
            value: saleInquiryForm.deptName,
          ),
          CryInput(
            width: 300,
            label: '报价单编号',
            enable: false,
            value: saleInquiryForm.inquiryNo,
          ),
          CryInput(
            width: 300,
            label: '业务员',
            enable: false,
            value: saleInquiryForm.userName,
          ),
          CryInput(
            width: 300,
            label: '询价单位',
            enable: false,
            value: saleInquiryForm.partnerName,
          ),
          CryInput(
            width: 300,
            label: '电话',
            enable: false,
            value: saleInquiryForm.phone,
          ),
          CryInput(
            width: 300,
            label: '客户性质',
            enable: false,
            value: saleInquiryForm.customerNature,
          ),
          CryInput(
            width: 300,
            label: '邮箱',
            enable: false,
            value: saleInquiryForm.email,
          ),
          CryInput(
            width: 300,
            label: '付费方式',
            enable: false,
            value: saleInquiryForm.paymentMethod,
          ),
          CryInput(
            width: 300,
            label: '项目名称',
            enable: false,
            value: saleInquiryForm.projectName,
          ),
          CryInput(
            width: 300,
            label: '是否有目标价',
            enable: false,
            value: saleInquiryForm.arrivalPlace == '1' ? '是' : '否',
          ),
          CryInput(
            width: 300,
            label: '到货地点',
            enable: false,
            value: saleInquiryForm.arrivalPlace,
          ),
          // 新增字段开始；
          CryInput(
            width: 300,
            label: '报价币种',
            enable: false,
            value: saleInquiryForm.currency,
            onSaved: (v) {
              saleInquiryForm.currency = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '下单汇率',
            enable: false,
            value: saleInquiryForm.exchangeRate,
            onSaved: (v) {
              saleInquiryForm.exchangeRate = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '税率',
            enable: false,
            value: saleInquiryForm.taxRate,
            onSaved: (v) {
              saleInquiryForm.taxRate = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '利润率',
            enable: false,
            value: saleInquiryForm.profitMargin,
            onSaved: (v) {
              saleInquiryForm.profitMargin = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '运输费用（元）',
            enable: false,
            value: saleInquiryForm.trafficExpense,
            onSaved: (v) {
              saleInquiryForm.trafficExpense = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '海运费/空运费（元）',
            enable: false,
            value: saleInquiryForm.oceanFreight,
            onSaved: (v) {
              saleInquiryForm.oceanFreight = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '运输保险（元）',
            enable: false,
            value: saleInquiryForm.transportationInsurance,
            onSaved: (v) {
              saleInquiryForm.transportationInsurance = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '保函费用（元）',
            enable: false,
            value: saleInquiryForm.guaranteeFee,
            onSaved: (v) {
              saleInquiryForm.guaranteeFee = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '熏蒸/热处理费（元）',
            enable: false,
            value: saleInquiryForm.heatTreatment,
            onSaved: (v) {
              saleInquiryForm.heatTreatment = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '报检代理费（元）',
            enable: false,
            value: saleInquiryForm.brokerageFee,
            onSaved: (v) {
              saleInquiryForm.brokerageFee = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '普惠制产地证（元）',
            enable: false,
            value: saleInquiryForm.COOFG,
            onSaved: (v) {
              saleInquiryForm.COOFG = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '试验费（元）',
            enable: false,
            value: saleInquiryForm.experimentalExpenses,
            onSaved: (v) {
              saleInquiryForm.experimentalExpenses = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '认证、公证费（元）',
            enable: false,
            value: saleInquiryForm.notarialFees,
            onSaved: (v) {
              saleInquiryForm.notarialFees = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '佣金（元）',
            enable: false,
            value: saleInquiryForm.commission,
            onSaved: (v) {
              saleInquiryForm.commission = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '厂验（元）',
            enable: false,
            value: saleInquiryForm.factoryInspection,
            onSaved: (v) {
              saleInquiryForm.factoryInspection = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '融资费用（元）',
            enable: false,
            value: saleInquiryForm.financing,
            onSaved: (v) {
              saleInquiryForm.financing = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '信用保险（元）',
            enable: false,
            value: saleInquiryForm.creditInsurance,
            onSaved: (v) {
              saleInquiryForm.creditInsurance = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '施工服务费（元）',
            enable: false,
            value: saleInquiryForm.constructionServiceFee,
            onSaved: (v) {
              saleInquiryForm.constructionServiceFee = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '其他费（元）',
            enable: false,
            value: saleInquiryForm.other,
            onSaved: (v) {
              saleInquiryForm.other = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CryInputNum(
            width: 300,
            label: '资信调查报告费（元）',
            enable: false,
            value: saleInquiryForm.surveyReport,
            onSaved: (v) {
              saleInquiryForm.surveyReport = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '费用合计（元）',
            enable: false,
            value: saleInquiryForm.amountTotal,
            onSaved: (v) {
              saleInquiryForm.amountTotal = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '毛利润（元）',
            enable: false,
            value: saleInquiryForm.grossProfit,
            onSaved: (v) {
              saleInquiryForm.grossProfit = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          // 新增字段结束；
          CryInput(
            label: '备注',
            enable: false,
            value: saleInquiryForm.comment,
          ),
        ],
      ),
    );
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('价格是否调整')),
        DataColumn(label: Text('产品编码(图号)')),
        DataColumn(label: Text("产品名称")),
        DataColumn(label: Text("规格型号")),
        DataColumn(label: Text("技术要求")),
        DataColumn(label: Text("备注")),
        DataColumn(label: Text("数量")),
        DataColumn(label: Text("单价(元)")),
        DataColumn(label: Text("小计(元)")),
        DataColumn(label: Text('退税率')),
        DataColumn(label: Text('销售单价（外币）')),
        DataColumn(label: Text('核算含税价格（元）')),
        DataColumn(label: Text('核算不含税价格（元）')),
        DataColumn(label: Text('单位补税及税金附加（元）')),
        DataColumn(label: Text('单项利润率%')),
        DataColumn(label: Text('单项换汇成本')),
      ],
      getCells: (m) {
        SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct.fromMap(m);
        return [
          DataCell(Text(saleInquiryProduct.edit == '1'?'是':'否')),
          DataCell(Text(saleInquiryProduct.productCode ?? '--')),
          DataCell(Text(saleInquiryProduct.productName ?? '--')),
          DataCell(Text(saleInquiryProduct.description ?? '--')),
          DataCell(Text(saleInquiryProduct.technicalRequirement ?? '--')),
          DataCell(Text(saleInquiryProduct.comment ?? '--')),
          DataCell(Text(saleInquiryProduct.quantity != null
              ? saleInquiryProduct.quantity.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.unitPrice != null
              ? saleInquiryProduct.unitPrice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.sum ?? '--')),
          DataCell(Text(saleInquiryProduct.taxrate != null
              ? saleInquiryProduct.taxrate.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.foreignprice != null
              ? saleInquiryProduct.foreignprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.taxinclusiveprice != null
              ? saleInquiryProduct.taxinclusiveprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.notaxinclusiveprice != null
              ? saleInquiryProduct.notaxinclusiveprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.taxsurcharges != null
              ? saleInquiryProduct.taxsurcharges.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.singleprofitmargin != null
              ? saleInquiryProduct.singleprofitmargin.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.summarycost != null
              ? saleInquiryProduct.summarycost.toString()
              : '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButton(
            label: '获取最新价格',
            iconData: Icons.add,
            onPressed: () => _getNewPrice()),
        CryButton(
            label: '报价调整',
            iconData: Icons.edit,
            onPressed: selectedList.length != 1
                ? null
                : () => _edit(selectedList[0], false)),
      ],
    );
    var buttonBottom = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            SaleInquiryFormOdooApi.saveFinished(
                saleInquiryForm.toOdooSavePriceFinished()).then((ResponseBodyApi res){
              if(res.success!){
                Navigator.pop(context, true);
              }
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
        key: scaffoldStateKey,
        appBar: AppBar(
          leading: Builder(
            builder: (BuildContext context) {
              final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
              final bool canPop = parentRoute?.canPop ?? false;

              if (canPop) {
                return BackButton();
              } else {
                return SizedBox.shrink();
              }
            },
          ),
          title: Text('报价单明细信息'),
        ),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(height: 10),
              isDisplayDesktop(context) ? form : Container(),
              isDisplayDesktop(context) ? buttonBar : Container(),
              SingleChildScrollView(child: table),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [buttonBottom],
              )
            ],
          ),
        ));
    return result;
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _getNewPrice() async {
    cryConfirm(context, "是否获取所有的产品最新报价信息？", (context) async {
      var result = await SaleInquiryFormOdooApi.getPrice(num.parse(saleInquiryForm.id!));
      if (result.success!) {
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _edit(SaleInquiryProduct? saleInquiryProduct, bool isAdd) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        child: SaleOfferPrice(
          saleInquiryProduct: saleInquiryProduct,
          isAdd: isAdd,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (saleInquiryProduct == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _loadData() async {
    saleInquiryProduct.inquiryNo = widget.saleInquiryForm!.inquiryNo.toString();
    saleInquiryProduct.partnerId = widget.saleInquiryForm!.partnerId.toString();
    saleInquiryProduct.partnerName =
        widget.saleInquiryForm!.partnerName.toString();
    saleInquiryProduct.userId = widget.saleInquiryForm!.userId.toString();
    saleInquiryProduct.userName = widget.saleInquiryForm!.userName.toString();
    saleInquiryProduct.inquiryId = widget.saleInquiryForm!.id.toString();
    ResponseBodyApi responseBodyApi =
        await SaleInquiryProductOdooApi.page(data: {
      "page": page,
      "domainList": saleInquiryProduct.toDomainList(),
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      // tableList = responseBodyApi.data;
      tableKey.currentState!.loadData(page);
      setState(() {});
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<SaleInquiryProduct>((e) => SaleInquiryProduct.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.add) {
          _edit(selectedList[0], true);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0], false);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            enabled: selectedList.length == 1,
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
      ],
    );
  }
}
